<template>
  <div class="flex flex-wrap gap-4" >
    <el-breadcrumb style="margin-bottom: 20px;">
    <el-breadcrumb-item><b>数据筛选</b></el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 信息搜索 -->
    <el-card style="width: 1800px" shadow="always">
      <el-button type="success" plain @click="dialogFormVisible = true" style="margin-bottom: 25px;">高级搜索</el-button>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="采购单号">
      <el-input v-model="formInline.purchase_Number" placeholder="请输入/扫描单号" clearable />
      </el-form-item>

      <el-form-item label="产品编号">
      <el-input v-model="formInline.product_Number" placeholder="请输入/扫描单号" clearable />
      </el-form-item>

      <el-form-item label="产品名称">
      <el-input v-model="formInline.product_Name" placeholder="请输入/扫描单号" clearable />
      </el-form-item>

      <el-form-item label="订单状态">
      <el-select
      v-model="formInline.purchase_Return"
      placeholder="请选择"
      clearable
      >
      <el-option label="Zone one" value="shanghai" />
      <el-option label="Zone two" value="beijing" />
      </el-select>
      </el-form-item>

      <el-form-item>
      <el-button type="primary" @click="purchaseshow()">搜索</el-button>
      <el-button  @click="onSubmit">重置</el-button>
      </el-form-item>
      </el-form>
    </el-card>
  </div>

  <!-- 列表显示信息 -->
  <div class="flex flex-wrap gap-4" style="margin-top: 20px;">
    <el-button type="success" @click="handleClick">+新增</el-button>
    <el-button type="warning" @click="handleEdit" :disabled="selectedIds.length !== 1">编辑</el-button>
    <el-button type="danger" @click="delall()">批量删除</el-button>
    <el-button type="info" @click="purchaseshow()">刷新</el-button>
    <el-button type="primary" @click="handleExport">导出</el-button>
    
    <!-- 复选框操作按钮 -->
    <el-button size="small" @click="clearSelection">清空选择</el-button>
    <el-button size="small" @click="toggleSelection">全选/反选</el-button>
    <el-button size="small" @click="showSelectedInfo">查看选中</el-button>
    <el-button size="small" type="warning" @click="showDeleteIds">查看删除数组</el-button>
    <el-card style="width: 1800px" shadow="always">
        <el-table 
          :data="tableData" 
          border 
          style="width: 100%"
          @selection-change="handleSelectionChange"
          ref="tableRef"
        >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="purchase_Number" label="订单号" width="100" />
        <el-table-column prop="product_Name" label="产品名称" width="100" />
        <el-table-column prop="product_Number" label="产品编号" width="100" />
        <el-table-column prop="specifications" label="产品规格" width="100" />
        <el-table-column prop="storage_Unit" label="单位" width="100" />
        <el-table-column prop="price" label="单价" width="100" />
        <el-table-column prop="product_Num" label="数量" width="100" />
        <!-- <el-table-column prop="date" label="总额" width="100" /> -->
        <el-table-column prop="carrier_Number" label="供应商编号" width="100" />
        <el-table-column prop="carrier_Name" label="供应商名称" width="100" />
        <el-table-column label="订单总额" width="100">
          <template #default="scope">
            {{ calculateTotalAmount(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="purchase_State" label="状态" width="100" />
        <el-table-column prop="be_Credited" label="是否入账" width="100" />
        <el-table-column label="退货" width="100">
          <template #default="scope">
            {{ scope.row.purchase_Return ? '否' : '是' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="100" />
        <el-table-column  label="操作"  width="380">
          <template v-slot="scoped">
            <el-button type="info" @click="viewDetails(scoped.row)">查看</el-button>
            <el-button 
              v-if="scoped.row.purchase_State !== '全部入库'" 
              type="success"
              @click="handleInbound(scoped.row)"
            >入库</el-button>
            <!-- <el-button type="danger" @click="updel(scoped.row.Id)">删除</el-button> -->
              <el-button type="danger" @click="open(scoped.row.id || 0)">删除</el-button>
            <el-button type="warning" @click="handleReturn(scoped.row)">退货</el-button>
            <el-button type="primary">入账</el-button>
          </template>
        </el-table-column>
        </el-table>
      <!-- 分页数据的显示 -->
      <el-pagination
      v-model:current-page="data.PageIndex"
      v-model:page-size="data.PageSize"
      :page-sizes="[15, 20, 25, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      prev-text="上一页"
      next-text="下一页"
      :total="data.totaCount"
      />

    </el-card>
  </div>



  <!-- 高级搜索弹出框 -->
  <el-dialog v-model="dialogFormVisible" title="高级搜索" width="500">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="采购单号">
    <el-input v-model="formInline.purchase_Number" placeholder="请输入/扫描单号" clearable />
    </el-form-item>

    <el-form-item label="产品编号">
    <el-input v-model="formInline.product_Number" placeholder="请输入/扫描单号" clearable />
    </el-form-item>

    <el-form-item label="产品名称">
    <el-input v-model="formInline.product_Name" placeholder="请输入供应商编号" clearable />
    </el-form-item>

    <el-form-item label="供应商名称">
    <el-input v-model="formInline.carrier_Name" placeholder="请输入供应商编号" clearable />
    </el-form-item>


    <el-form-item label="起始时间">
    <el-date-picker
    v-model="formInline.createTime"
    type="date"
    placeholder="起始时间"
    clearable
    />
    </el-form-item>
    <el-form-item>
    <el-button type="primary" @click="purchaseshow()">查询</el-button>
    </el-form-item>
    </el-form>
    <!-- <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">
          Confirm
        </el-button>
      </div>
    </template> -->
  </el-dialog>

  <!-- 采购详情查看弹出框 -->
  <el-dialog v-model="detailDialogVisible" title="采购入库" width="1200" draggable>
    <div v-if="selectedRow">
      <!-- 订单和供应商信息 -->
      <el-card style="margin-bottom: 20px;">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">订单号：</span>
              <span class="value">{{ selectedRow.purchase_Number }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">单据类型：</span>
              <span class="value">{{ selectedRow.purchase__Types || '实际订单' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">单据状态：</span>
              <span class="value">{{ selectedRow.purchase_State || '创建订单' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">关联单号：</span>
              <span class="value">{{ selectedRow.order_Number || '00071' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">制单人：</span>
              <span class="value">{{ selectedRow.purchase__Preparer || '张丽' }}</span>
            </div>
          </el-col>

          <!-- <el-col :span="8">
            <div class="detail-item">
              <span class="label">制单日期：</span>
              <span class="value">{{ formatDate(selectedRow.createTime) }}</span>
            </div>
          </el-col> -->

        </el-row>
        <el-row :gutter="20">

          <!-- <el-col :span="8">
            <div class="detail-item">
              <span class="label">发货日期：</span>
              <span class="value">{{ formatDate(selectedRow.purchase__Day) }}</span>
            </div>
          </el-col> -->

          <el-col :span="8">
            <div class="detail-item">
              <span class="label">供应商编号：</span>
              <span class="value">{{ selectedRow.carrier_Number || '0112' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">供应商名称：</span>
              <span class="value">{{ selectedRow.carrier_Name || '北京' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">联系人：</span>
              <span class="value">{{ selectedRow.contact_Name || '张丽' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">电话：</span>
              <span class="value">{{ selectedRow.purchase__Phone || '15268945864' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">备注：</span>
              <span class="value">{{ selectedRow.purchase__Desc || '北京' }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 产品列表 -->
      <el-card>
        <div style="margin-bottom: 15px; font-weight: bold;">产品信息</div>
        <el-table :data="productList" border style="width: 100%">
          <el-table-column prop="product_Number" label="产品编码" width="100" />
          <el-table-column prop="product_Name" label="产品名称" width="120" />
          <el-table-column prop="specifications" label="规格" width="80" />
          <el-table-column prop="storage_Unit" label="单位" width="80" />
          <el-table-column prop="product_Num" label="数量" width="80" />
          <el-table-column prop="batch" label="批次" width="80" />
          <el-table-column prop="inbound_Num" label="入库数" width="100" />
          <el-table-column prop="warehouse_Location" label="库位" width="150" />
          <el-table-column prop="price" label="单价" width="80" />
          <el-table-column prop="total_Amount" label="总额" width="100" />
        </el-table>
      </el-card>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="detailDialogVisible = false">确认</el-button>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 采购入库弹出框 -->
  <el-dialog v-model="inboundDialogVisible" title="采购入库" width="1400" draggable>
    <div v-if="inboundRow">
      <!-- 订单和供应商信息 -->
      <el-card style="margin-bottom: 20px;">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">订单号：</span>
              <span class="value">{{ inboundRow.purchase_Number }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">单据类型：</span>
              <span class="value">{{ inboundRow.purchase__Types || '实际订单' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">单据状态：</span>
              <span class="value">{{ inboundRow.purchase_State || '创建订单' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">关联单号：</span>
              <span class="value">{{ inboundRow.order_Number || '00071' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">制单人：</span>
              <span class="value">{{ inboundRow.purchase__Preparer || '张丽' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">制单日期：</span>
              <span class="value">{{ formatDate(inboundRow.createTime) }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">发货日期：</span>
              <span class="value">{{ formatDate(inboundRow.purchase__Day) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">供应商编号：</span>
              <span class="value">{{ inboundRow.carrier_Number || '0112' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">供应商名称：</span>
              <span class="value">{{ inboundRow.carrier_Name || '北京' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">联系人：</span>
              <span class="value">{{ inboundRow.contact_Name || '张丽' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">电话：</span>
              <span class="value">{{ inboundRow.purchase__Phone || '15268945864' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">备注：</span>
              <span class="value">{{ inboundRow.purchase__Desc || '北京' }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 产品入库信息表格 -->
      <el-card>
        <div style="margin-bottom: 15px; font-weight: bold;">产品入库信息</div>
        <el-table :data="inboundProductList" border style="width: 100%">
          <el-table-column prop="product_Number" label="产品编码" width="120" />
          <el-table-column prop="product_Name" label="产品名称" width="150" />
          <el-table-column prop="specifications" label="规格" width="80" />
          <el-table-column prop="storage_Unit" label="单位" width="80" />
          <el-table-column prop="product_Num" label="数量" width="80" />
          <el-table-column label="批次" width="120">
            <template #default="scope">
              <el-input 
                v-model="scope.row.batch" 
                placeholder="输入批次" 
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column label="入库数" width="120">
            <template #default="scope">
              <el-input 
                v-model="scope.row.inbound_Num" 
                placeholder="输入入库数量" 
                size="small"
                type="number"
                @input="calculateInboundTotal(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="库位" width="150">
            <template #default="scope">
              <el-input 
                v-model="scope.row.warehouse_Location" 
                placeholder="请输入库位" 
                size="small"
              />
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" width="80" />
          <el-table-column label="总额" width="100">
            <template #default="scope">
              {{ calculateInboundTotal(scope.row) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirmInbound">确认</el-button>
        <el-button @click="inboundDialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 采购退货弹出框 -->
  <el-dialog v-model="returnDialogVisible" title="采购退货" width="1400" draggable>
    <div v-if="returnRow">
      <!-- 订单和供应商信息 -->
      <el-card style="margin-bottom: 20px;">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">订单号：</span>
              <span class="value">{{ returnRow.purchase_Number }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">单据类型：</span>
              <span class="value">{{ returnRow.purchase__Types || '实际订单' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">单据状态：</span>
              <span class="value">{{ returnRow.purchase_State || '创建订单' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">关联单号：</span>
              <span class="value">{{ returnRow.order_Number || '00071' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">制单人：</span>
              <span class="value">{{ returnRow.purchase__Preparer || '张丽' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">制单日期：</span>
              <span class="value">{{ formatDate(returnRow.createTime) }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">发货日期：</span>
              <span class="value">{{ formatDate(returnRow.purchase__Day) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">供应商编号：</span>
              <span class="value">{{ returnRow.carrier_Number || '0112' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">供应商名称：</span>
              <span class="value">{{ returnRow.carrier_Name || '北京' }}</span>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">联系人：</span>
              <span class="value">{{ returnRow.contact_Name || '张丽' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">电话：</span>
              <span class="value">{{ returnRow.purchase__Phone || '15268945864' }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="detail-item">
              <span class="label">备注：</span>
              <span class="value">{{ returnRow.purchase__Desc || '北京' }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 产品退货信息表格 -->
      <el-card>
        <div style="margin-bottom: 15px; font-weight: bold;">产品退货信息</div>
        <el-table :data="returnProductList" border style="width: 100%">
          <el-table-column prop="product_Number" label="产品编码" width="120" />
          <el-table-column prop="product_Name" label="产品名称" width="150" />
          <el-table-column prop="specifications" label="规格" width="80" />
          <el-table-column prop="storage_Unit" label="单位" width="80" />
          <el-table-column prop="product_Num" label="数量" width="80" />
          <el-table-column prop="batch" label="批次" width="80" />
          <el-table-column label="退货数" width="120">
            <template #default="scope">
              <el-input 
                v-model="scope.row.return_Num" 
                placeholder="输入数量" 
                size="small"
                type="number"
                @input="calculateReturnTotal(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" width="80" />
          <el-table-column label="总额" width="100">
            <template #default="scope">
              {{ calculateReturnTotal(scope.row) }}
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirmReturn">确认</el-button>
        <el-button @click="returnDialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script lang="ts" setup>
import { reactive, ref, onMounted,watch } from 'vue'
import { BusinessRed } from '@/http/axiosHelper'
import { BusinessWrite } from '@/http/axiosHelper'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

// 定义类型接口
interface PurchaseData {
  id?: number
  purchase_Number?: string
  product_Name?: string
  product_Number?: string
  specifications?: string
  storage_Unit?: string
  price?: number
  product_Num?: number
  carrier_Number?: string
  carrier_Name?: string
  name?: string
  purchase_State?: string
  be_Credited?: boolean
  purchase_Return?: boolean
  createTime?: string
  purchase__Types?: string
  order_Number?: string
  purchase__Preparer?: string
  purchase__Day?: string
  contact_Name?: string
  purchase__Phone?: string
  purchase__Desc?: string
}

interface ProductData {
  product_Number: string
  product_Name: string
  specifications: string
  storage_Unit: string
  product_Num: number
  batch: string
  inbound_Num: number
  warehouse_Location: string
  price: number
  total_Amount: number
  return_Num?: number  // 添加退货数量属性
}
const router = useRouter();



//生命周期钩子函数
onMounted(()=>{
  purchaseshow();
})

//采购信息新增页面
const handleClick = () => {
  router.push({name:'PurchAddShow'})
}

//采购信息编辑页面
const handleEdit = () => {
  // 检查是否只选中了一条记录
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请先选择要编辑的记录');
    return;
  }
  
  if (selectedIds.value.length > 1) {
    ElMessage.warning('只能编辑一条记录，请重新选择');
    return;
  }
  
  // 获取选中的记录数据
  const selectedId = selectedIds.value[0];
  const selectedData = selectedRows.value.find(row => row.id === selectedId);
  
  if (!selectedData) {
    ElMessage.error('未找到选中的记录数据');
    return;
  }
  
  // 将选中的数据存储到localStorage，以便编辑页面使用
  localStorage.setItem('editPurchaseData', JSON.stringify(selectedData));
  
  // 跳转到编辑页面，并传递ID参数
  router.push({
    name: 'PurchAddShow',
    query: { 
      mode: 'edit',
      id: selectedId.toString()
    }
  });
}

//数据信息的显示
const data = ref<{
    PageIndex: number
    PageSize: number
    totaCount: number
    Purchase_Number: string
    Product_Number: string
    Product_Name: string
    Purchase__Supplier: string
}>({
    PageIndex: 1,
    PageSize: 15,
    totaCount: 0,
    Purchase_Number: '',
    Product_Number: '',
    Product_Name: '',
    Purchase__Supplier: ''
})
const tableData = ref<PurchaseData[]>([])
const purchaseshow = () => {
   BusinessRed.get("api/Purchase/PurchaseShow", {
        params: {
            PageIndex: data.value.PageIndex,
            PageSize: data.value.PageSize,
            purchase_Number:formInline.purchase_Number,
            product_Number:formInline.product_Number,
            product_Name:formInline.product_Name,
            carrier_Name:formInline.carrier_Name
        }
    })
        .then((res: any) => {
            tableData.value = res.data.data;
            data.value.totaCount = res.data.totaCount
        })
        .catch((err: any) => {
            ElMessage.error("查询失败")
            console.error(err)
        })
}


//分页监听事件
watch([() => data.value.PageIndex, () => data.value.PageSize], () => {
  purchaseshow();
}, { deep: true })




// 导出函数（假设已配置 Axios 拦截器自动添加 Token）
const handleExport = async () => {
    try {
        // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
        const response = await BusinessRed({
            url: '/api/Purchase/GetSellExport', // 后端接口地址
            method: 'GET',
            params: {
                PageIndex: data.value.PageIndex,
                PageSize: data.value.PageSize,
                Product_Number: data.value.Product_Number,
                Product_Name: data.value.Product_Name,
                Purchase_Number: data.value.Purchase_Number,
                Purchase__Supplier: data.value.Purchase__Supplier,
            }, // 对应后端 [FromQuery] 的 command 参数
            responseType: 'blob', // 关键：指定响应类型为二进制流（Excel 文件）
        } as any);

        // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
        const fileName = getFileNameFromHeaders((response as any).headers);

        // 3. 生成下载链接并触发下载
        const blob = new Blob([response.data], {
            type: response.headers['content-type'] || 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName; // 文件名从响应头获取或自定义
        document.body.appendChild(a);
        a.click();

        // 4. 清理资源
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);

    } catch (error: any) {
        // 处理错误（如后端返回 401/400 等）
        console.error('导出失败：', error.response?.data || error.message);
        ElMessage.error('导出失败，请检查参数或重新登录');
    }
}

// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers: any) {
    const contentDisposition = headers['content-disposition'] || headers['Content-Disposition'];
    if (!contentDisposition) return '可出库存.xlsx'; // 默认文件名

    // 解码文件名（处理中文编码问题）
    const match = contentDisposition.match(/filename\*?=([^;]+)/);
    if (match) {
        return decodeURIComponent(match[1].replace(/["']/g, ''));
    }
    return '可出库存.xlsx';
}



//高级搜索弹出框
const dialogFormVisible = ref(false)

//详情查看弹出框
const detailDialogVisible = ref(false)
const selectedRow = ref<PurchaseData | null>(null)
const productList = ref<ProductData[]>([])

//入库弹出框相关
const inboundDialogVisible = ref(false)
const inboundRow = ref<PurchaseData | null>(null)
const inboundProductList = ref<ProductData[]>([])

//退货弹出框相关
const returnDialogVisible = ref(false)
const returnRow = ref<PurchaseData | null>(null)
const returnProductList = ref<ProductData[]>([])

//表格复选框相关
const tableRef = ref<any>()
const selectedRows = ref<PurchaseData[]>([])
const selectedIds = ref<number[]>([])

// 自定义删除ID数组
const deleteIds = ref<number[]>([])

//条件查询
const formInline = reactive<{
  purchase_Number: string
  product_Number: string
  product_Name: string
  carrier_Name: string
  createTime: string
  purchase_Return: string
}>({
  purchase_Number: '',
  product_Number: '',
  product_Name: '',
  carrier_Name: '',
  createTime: '',
  purchase_Return: ''
})


//显示信息的删除
const open = (id: number) => {
  ElMessageBox.confirm(
    '该操作将删除该数据,确定要删除吗？',
    '确认提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
           console.log(id)
      BusinessWrite.post('/api/Purchase/DelPurchase',{id:id})
      
      .then((res: any)=>{
         
          if(res.data.code==200)
          {
            ElMessage.success("删除成功");
            purchaseshow();
          }
          else
          {
            ElMessage.error("删除失败");
          }
      })
      .catch((err: any) => {
        ElMessage.error("删除失败");
        console.error(err);
      })
    })
    .catch(() => {
      ElMessage.info('删除取消')
    })
}




const onSubmit = () => {
  // 重置表单
  formInline.purchase_Number = ''
  formInline.product_Number = ''
  formInline.product_Name = ''
  formInline.carrier_Name = ''
  formInline.createTime = ''
  formInline.purchase_Return = ''
  // 重新加载数据
  purchaseshow()
}

//查看详情
const viewDetails = (row: PurchaseData) => {
  selectedRow.value = row;
  // 模拟产品数据，实际应该从API获取
  productList.value = [
    {
      product_Number: row.product_Number || '000187',
      product_Name: row.product_Name || '设备箱',
      specifications: row.specifications || '个',
      storage_Unit: row.storage_Unit || '吨',
      product_Num: row.product_Num || 1523,
      batch: '10000',
      inbound_Num: 140000,
      warehouse_Location: '默认待入库位',
      price: row.price || 100,
      total_Amount: (row.price || 100) * (row.product_Num || 1523)
    } as ProductData
  ];
  detailDialogVisible.value = true;
}

//处理入库
const handleInbound = (row: PurchaseData) => {
  inboundRow.value = row;
  // 初始化入库产品列表
  inboundProductList.value = [
    {
      product_Number: row.product_Number || '000187',
      product_Name: row.product_Name || '设备箱',
      specifications: row.specifications || '个',
      storage_Unit: row.storage_Unit || '吨',
      product_Num: row.product_Num || 1523,
      batch: '',
      inbound_Num: 0,
      warehouse_Location: '',
      price: row.price || 100,
      total_Amount: 0
    } as ProductData
  ];
  inboundDialogVisible.value = true;
}

//计算入库总额
const calculateInboundTotal = (row: ProductData) => {
  const price = row.price || 0;
  const inboundNum = row.inbound_Num || 0;
  const total = price * inboundNum;
  row.total_Amount = total;
  return total.toFixed(2);
}

//确认入库
const confirmInbound = () => {
  // 验证必填字段
  const hasEmptyFields = inboundProductList.value.some(item => 
    !item.batch || !item.inbound_Num || !item.warehouse_Location
  );
  
  if (hasEmptyFields) {
    ElMessage.warning('请填写完整的入库信息（批次、入库数、库位）');
    return;
  }
  
  // 验证入库数量不能超过订单数量
  const hasInvalidQuantity = inboundProductList.value.some(item => 
    (item.inbound_Num || 0) > (item.product_Num || 0)
  );
  
  if (hasInvalidQuantity) {
    ElMessage.warning('入库数量不能超过订单数量');
    return;
  }
  
  // 这里可以调用后端API进行入库操作
  ElMessage.success('入库操作成功');
  inboundDialogVisible.value = false;
  
  // 刷新列表数据
  purchaseshow();
}

//处理退货
const handleReturn = (row: PurchaseData) => {
  returnRow.value = row;
  // 初始化退货产品列表
  returnProductList.value = [
    {
      product_Number: row.product_Number || '000187',
      product_Name: row.product_Name || '设备箱',
      specifications: row.specifications || '个',
      storage_Unit: row.storage_Unit || '吨',
      product_Num: row.product_Num || 1523,
      batch: '15222', // 模拟批次号
      return_Num: 0,
      warehouse_Location: '',
      price: row.price || 100,
      total_Amount: 0,
      inbound_Num: 0  // 添加缺失的属性
    } as ProductData
  ];
  returnDialogVisible.value = true;
}

//计算退货总额
const calculateReturnTotal = (row: ProductData) => {
  const price = row.price || 0;
  const returnNum = row.return_Num || 0;
  const total = price * returnNum;
  row.total_Amount = total;
  return total.toFixed(2);
}

//确认退货
const confirmReturn = () => {
  // 验证必填字段
  const hasEmptyFields = returnProductList.value.some(item => 
    !item.return_Num || item.return_Num === 0
  );
  
  if (hasEmptyFields) {
    ElMessage.warning('请填写退货数量');
    return;
  }
  
  // 验证退货数量不能超过订单数量
  const hasInvalidQuantity = returnProductList.value.some(item => 
    (item.return_Num || 0) > (item.product_Num || 0)
  );
  
  if (hasInvalidQuantity) {
    ElMessage.warning('退货数量不能超过订单数量');
    return;
  }
  
  // 准备退货数据
  const returnData = {
    returnOrder: returnRow.value,
    returnProducts: returnProductList.value.map(item => ({
      ...item,
      return_Amount: item.total_Amount
    }))
  };
  
  // 将退货数据存储到localStorage，以便退货页面使用
  localStorage.setItem('returnData', JSON.stringify(returnData));
  
  // 显示成功消息
  ElMessage.success('退货信息已提交，正在跳转到退货页面...');
  
  // 关闭退货弹出框
  returnDialogVisible.value = false;
  
  // 跳转到采购退货页面
  router.push({ name: 'PurchreturnShow' });
}

//计算订单总额
const calculateTotalAmount = (row: PurchaseData) => {
  const price = row.price || 0;
  const quantity = row.product_Num || 0;
  return (price * quantity).toFixed(2);
}

//格式化日期
const formatDate = (dateString: string | undefined) => {
  if (!dateString) return '';
  try {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (error: any) {
    return dateString;
  }
}

//处理复选框选择变化
const handleSelectionChange = (selection: PurchaseData[]) => {
  selectedRows.value = selection;
  selectedIds.value = selection.map(row => row.id || 0).filter(id => id !== 0);
  
  // 同时更新自定义删除ID数组
  deleteIds.value = [...selectedIds.value];
  
  console.log('选中的行数据:', selectedRows.value);
  console.log('选中的ID列表:', selectedIds.value);
  console.log('删除ID数组:', deleteIds.value);
  
  // 显示选中的信息
  if (selectedIds.value.length > 0) {
    ElMessage.info(`已选中 ${selectedIds.value.length} 条记录，ID: ${selectedIds.value.join(', ')}`);
  }
}



//清空选择
const clearSelection = () => {
  if (tableRef.value) {
    (tableRef.value as any).clearSelection();
  }
  // 同时清空所有相关数组
  selectedIds.value = [];
  selectedRows.value = [];
  deleteIds.value = [];
  console.log('已清空所有选择');
}

//切换全选状态
const toggleSelection = () => {
  if (tableRef.value) {
    (tableRef.value as any).toggleAllSelection();
  }
}

//显示选中信息
const showSelectedInfo = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.info('当前没有选中任何记录');
    return;
  }
  
  const info = selectedRows.value.map(row => 
    `ID: ${row.id}, 订单号: ${row.purchase_Number}, 产品: ${row.product_Name}`
  ).join('\n');
  
  const deleteInfo = `\n\n待删除ID数组: [${deleteIds.value.join(', ')}]`;
  
  ElMessageBox.alert(
    info + deleteInfo,
    `选中的 ${selectedIds.value.length} 条记录详情`,
    {
      confirmButtonText: '确定',
      type: 'info',
    }
  );
}

//显示删除ID数组信息
const showDeleteIds = () => {
  if (deleteIds.value.length === 0) {
    ElMessage.info('删除数组为空');
    return;
  }
  
  ElMessageBox.alert(
    `删除ID数组: [${deleteIds.value.join(', ')}]\n数组长度: ${deleteIds.value.length}`,
    '删除数组状态',
    {
      confirmButtonText: '确定',
      type: 'warning',
    }
  );
}

//批量删除方法
const delall = () => {
  // 检查是否有选中的记录
  if (deleteIds.value.length === 0) {
    ElMessage.warning('请先选择要删除的记录');
    return;
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${deleteIds.value.length} 条记录吗？\nID: ${deleteIds.value.join(', ')}`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    console.log('准备删除的ID数组:', deleteIds.value);
    
    // 关键：后端API期望的是 List<int> Id，参数名是 Id（大写I）
    // 将选中的ID数组传递给API，参数名必须是 Id
    BusinessWrite.post('/api/Purchase/DelAll', {
      Id: deleteIds.value  // 传递ID数组，参数名是 Id
    })
    .then((res: any) => {
      if(res.data.code == 200) {
        ElMessage.success(`成功删除 ${deleteIds.value.length} 条记录`);
        
        // 清空所有相关数组
        deleteIds.value = [];
        selectedIds.value = [];
        selectedRows.value = [];
        
        // 清空表格选择并刷新数据
        clearSelection();
        purchaseshow();
      } else {
        ElMessage.error("删除失败：" + (res.data.message || '未知错误'));
      }
    })
    .catch((err: any) => {
      ElMessage.error("删除失败");
      console.error('删除API调用失败:', err);
    })
  })
  .catch(() => {
    ElMessage.info('已取消批量删除');
  })
}






</script>

<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
b{
  color: black;
}

.detail-item {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.detail-item .label {
  font-weight: bold;
  color: #606266;
  min-width: 100px;
  margin-right: 10px;
}

.detail-item .value {
  color: #303133;
  flex: 1;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
</style>